package com.kjs.web.jwt.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kjs.common.consts.ResultConst;
import com.kjs.common.resultModel.JsonResult;
import com.kjs.common.tools.StringChecker;
import com.kjs.execptionless.BusinessException;
import com.kjs.execptionless.ExceptionCode;
import com.kjs.execptionless.ExceptionMsg;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定401返回值
 */
@Component
@Slf4j
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        //response.setHeader("Access-Control-Allow-Origin", "*");
        //response.setStatus(401);
        String uriPath = request.getRequestURI();
//        String err = response.getHeader("err");
//        JSONObject jr = new JSONObject();
//        if (!StringChecker.isEmpty(err)){
//            jr.put("code", err);
//        }else {
////            jr.put("err", ResultConst.ERR_AUTH_SIGN_MISMATCH);
//            jr.put("code",400);
//        }
        String body = JSON.toJSONString(ExceptionMsg.Unauthorized);
        ResponseHelper.print(response, body, ExceptionCode.Unauthorized.value());
        log.warn("请求：{}，返回：{}", uriPath, body);
    }
}
